var db = openDatabase("d2r", "0.1", "小米路由下载插件脚本存储", 200000);
//script
// 检测表是否存在


function getD2rUrl(){
    var d2r = localStorage.getItem('d2r');
    if(d2r>0){
        return "http://midownload.sinaapp.com/d2r/"
    }else{
        return "https://d.miwifi.com/d2r/"
    }
        
}




function wildcard(pattern,word){
    var PATTERN_LINE_START = "^";
    var PATTERN_LINE_END = "$";
    var META_CHARACTERS = ['$', '^', '[', ']', '(', ')', '{', '}', '+', '.', '\\'];
    var result = PATTERN_LINE_START+'(';
    for(var i=0;i<pattern.length;i++){
        var ch = pattern.charAt(i);
        if(metaSearch(ch,META_CHARACTERS)){
            result += "\\" + ch;
            continue;
        }else{
            switch (ch) {
                case '*':
                    result += ".*";
                    break;
                case '?':
                    result += ".{0,1}";
                    break;
                default:
                    result += ch;
            }
        }
    }
    result += ')'+PATTERN_LINE_END;
    // console.log(result)
    if(word.match(result) == null){
        return false;   
    }
    return true;
}
function metaSearch(ch,META_CHARACTERS){
    
    for(var metaCh in META_CHARACTERS){
        if(ch == META_CHARACTERS[metaCh] ){
            return true;
        }
    }
    return false;
}








db.transaction( function(tx) {
    tx.executeSql(
        "SELECT COUNT(*)  as CNT FROM sqlite_master where type='table' and name='script'",
        [],
        function(tx, result){
            //如果没有表 创建并写入初始数据
            if((result.rows.item(0)['CNT'])==0){
                localStorage.setItem('d2r',1);

                // id 状态 标示 名字 摘要 规则 代码
                tx.executeSql(
                    "create table script ("+
                        "[id] integer PRIMARY KEY autoincrement,"+
                        "[server_id] int default 0, "+
                        "[version] real default 0, "+
                        "[status] int default 0, "+
                        "[file] text default '', "+
                        "[marked] text, "+
                        "[author] text, "+
                        "[mail] text, "+
                        "[name] text, "+
                        "[summary] text, "+
                        "[matching] text, "+
                        "[script] text, "+
                        "[error] text default '', "+
                        "[addtime] datetime default (datetime('now', 'localtime'))"+
                    ");",
                    [],
                    function(tx, result){
                        console.log('表创建完成',result);
                        tx.executeSql(
                            "INSERT INTO script (status,marked,name,summary,matching,script,author,mail,version,file) values(?, ?, ?, ?, ?, ?, ?, ?,?,?)",
                            [1,'baiduyun','百度网盘按钮','百度网盘增加下载按钮等','*://pan.baidu.com/*','console.log("ok")','小鑫','i@xioxin.com',1.1,'baiduyun.js'],
                            function(tx, result){
                                console.log('添加成功',result);
                            },
                            function(tx, error){}
                        )
                    },
                    function(tx, error){ console.log(error) }
                );
            }
        }, 
        function(tx, error){ console.log(error) }
    );
});


function drop_db(){
    db.transaction(function (tx) {  
        tx.executeSql('DROP TABLE script'); 
    });
}



var quanju = false;
var md = function callback(item)
      {
          if(!quanju){
              if(item.referrer!=src){
                  return;
              }
          }
        if (item.state == "complete" || item.state == "interrupted")
        {
          return;
        }

        href = item.url;
        xmd(href,item.referrer,name);

        // 取消chrome默认下载
        chrome.downloads.cancel(item.id);
        
        // 删除下载记录，有时默认下载会先执行，因为异步，防止出现默认下载框
        chrome.downloads.erase({id:item.id},
          function (ids)
          {
            //
          }
        );
        // 关闭chrome新建下载留存的tab
        chrome.tabs.query({url:item.url},
          function queryResult(tabArray)
          {
            if (tabArray[0])
            {
              chrome.tabs.remove(tabArray[0].id);
            }
          }
        );
          if(!quanju){
            chrome.downloads.onCreated.removeListener(md);
          }
      }
var name;
var src;
function xmd(_href,_src,_name){
    var href = getD2rUrl()+"?url=" + Base64.encodeURI(_href) + "&src="+encodeURIComponent(_src)+'&name='+encodeURIComponent(_name)
    window.open(href);
}

var api = {};
api['xmd'] = function(_name,_src){
    if(!quanju){
        /*存储为全局变量*/
        name = _name;
        src = _src;
        /*添加上事件 如果不是全局在调用一次后自动销毁*/
        chrome.downloads.onCreated.addListener(md);
    }
    return true;
}

//前台触发后台方法
chrome.extension.onRequest.addListener(
    function(request, sender, sendResponse){
        if(request.type=='fun'){
            var data = window['api'][request.fun].apply(window,request.data,sendResponse);
            if(!request.ajax){
                sendResponse({type: "return",fun:request.fun,data:data});
            }
        }
    }
);

function setquanju(var1){
    quanju = var1?true:false;
    chrome.downloads.onCreated.removeListener(md);
    chrome.browserAction.setBadgeText({text:''});
    if(quanju){
        chrome.browserAction.setBadgeText({text:'·'});
        chrome.downloads.onCreated.addListener(md);
    }
}

chrome.contextMenus.create({
    type:'normal',
    title :'下载到小米路由',
    contexts  :['link','selection'],
    onclick:function(e){
        var thisurl = e.linkUrl?e.linkUrl: e.selectionText;
        if(thisurl){
            xmd(thisurl,e.pageUrl,'');
        }
    }
});



chrome.tabs.onUpdated.addListener(function(tab_id,tab_status,tab) {
    if(tab_status.status!='complete'){return;}
    db.transaction( function(tx) {
        tx.executeSql(
            "SELECT * FROM script where `status`= 1",
            [],
            function(tx, result){
                var rows = result.rows, length = rows.length, i=0;
                for(i; i < length; i++) {
                    // console.log(rows.item(i)['matching'],tab.url)
                    if(wildcard(rows.item(i)['matching'],tab.url)){
                        // console.log('wildcard-YES')
                        // console.log(rows.item(i)['script']);
                        var code = ';;console.log("小米下载加载脚本：'+rows.item(i)['name']+'");;';
                        code += rows.item(i)['script']

                        // code = "var bg = chrome.extension.getBackgroundPage();console.log(bg);"; 
                        chrome.tabs.executeScript(tab_id,{file: "jquery.js"});
                        chrome.tabs.executeScript(tab_id,{file: "Base64.js"});
                        chrome.tabs.executeScript(tab_id,{file: "mdapi.js"});
                        var file = rows.item(i)['file'];
                        if(file){
                            chrome.tabs.executeScript(tab_id,{file: file});
                        }
                        chrome.tabs.executeScript(tab_id,{code:code});
                    }
                } 
            },
            function(tx, error){
                console.log('获取脚本列表时发生错误',error);
            }
        )
    });


 });